<!--
    * Time    : 2021-03-30 18:30:03
    * Author  : 李铧锐
    * Desc    : 自提点 - 自提点激活
-->
<template>
    <div class="w750 gray-body font-14 text-333 bg-fff">
        <div>
            <van-field
                v-model="pointName"
                name="自提点名称"
                label="自提点名称"
                placeholder="自提点名称"
                label-class="font-14"
                maxlength="20"
                clearable
            />
            <van-field v-model="contactPhone" type="number" name="联系电话" label="联系电话" placeholder="请填写自提点联系号码" maxlength="11" />
            <van-field :value="addressName" name="所在省市" label="所在省市" placeholder="省市区街道" readonly @click="goChoose">
                <template>
                    <input type="text" style="padding-left: 40px" class="item-btn text-ellipsis text-ccc" />
                </template>
            </van-field>

            <van-field
                :value="choosePoint.name"
                name="地理位置"
                label="地理位置"
                placeholder="请选择自提地址"
                right-icon="location"
                @click="goChooseAddress"
                readonly
                :rules="[{ required: true, message: '请选择自提地址', trigger: 'onChange' }]"
            >
                <template #right-icon>
                    <span class="location iconfont text-12 flex-1 pr-1 text-right" style="color: #000">&#xe651;</span>
                </template>
            </van-field>

            <!-- 详细地址 -->
            <van-field
                v-model="sinceMentionAddr"
                name="详细地址"
                label="详细地址"
                placeholder="请填写准确地址方便用户上门提货"
                label-class="font-14"
                clearable
            />

            <!-- 营业时间 -->
            <div class="user_info pl-1">
                <div class="flex-center border-bottom border-c-f8">
                    <span class="text-333 mr-15p" style="width: 6.2em">营业时间</span>
                    <div class="flex-1 d-flex flex-wrap a-center pt-1">
                        <div
                            class="rounded-13 mr mb-1 flex-center font-12"
                            :class="[period.indexOf(dayIndex + 1) > -1 ? ' text-main' : '']"
                            style="width: 60px; height: 26px"
                            :style="{
                                background: period.indexOf(dayIndex + 1) > -1 ? bg01 : '#f5f5f5',
                                border: period.indexOf(dayIndex + 1) > -1 ? `1px solid ${br04}` : 'none'
                            }"
                            v-for="(item, dayIndex) in daysList"
                            :key="dayIndex"
                            @click="toggleDay(dayIndex + 1)"
                        >
                            {{ item }}
                        </div>
                    </div>
                </div>

                <!-- 时间段 -->
                <div class="time-list">
                    <van-popup v-model="timeVisible" position="bottom" :style="{ height: '50%' }">
                        <van-datetime-picker type="time" :title="timeTitle" @confirm="confirmTime" @cancel="timeVisible = false" />
                    </van-popup>
                    <div class="time-item h-50p my-15p d-flex a-center" v-for="(item, timeIndex) in businessHours" :key="timeIndex">
                        <div style="flex: 0 0 6.2em" class="text-right pr-15">
                            <span v-if="timeIndex != 0" class="iconfont text-12 iconshanchu" @click="deleteTime(timeIndex)"></span>
                        </div>
                        <div class="flex-1 flex-between h-100">
                            <div class="flex-center">
                                <div class="text-666" @click="selectTime('选择开始时间', 'begin', timeIndex)">
                                    {{ item.begin || '请选择开始时间' }}
                                </div>
                                <div class="px-15p">~</div>
                                <div class="text-666" @click="selectTime('选择结束时间', 'end', timeIndex)">{{ item.end || '请选择结束时间' }}</div>
                            </div>
                            <span v-if="businessHours.length < 3" class="iconfont text-12 pr iconzengjia" @click="addTime(timeIndex)"></span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 自提点图片 -->
            <div class="border-top-10bg border-c-f8 bg-fff pl-1 pr-15 pb-150">
                <div class="mt-15p">
                    自提点图片
                    <div class="pt text-ccc pb-2">
                        请确保自提点照片清晰，保证用户能够找到您的提货点；
                        <br />
                        最多可上传3张
                    </div>
                    <template>
                        <drag-upload :limit="3" :delay="1500" ref="drag-upload" v-model="sinceMentionPic" />
                    </template>
                </div>
            </div>
        </div>
        <transition-group name="van-slide-up">
            <div :key="3" class="position-fixed text-fff w-100 font-14 bottom-0 left-0" style="padding: 6px 20px; z-index: 89">
                <div class="text-center">
                    <van-button round block :color="themes.color" native-type="button" @click="submit">确定</van-button>
                </div>
            </div>
        </transition-group>

        <address-select v-model="addressShow" title="地址" mode="id" @confirm="onAddress" :defaultValue="defaultValue" />
    </div>
</template>

<script>
import { mapState } from 'vuex'
import { colorRgb } from '@/utils/utils'
import addressSelect from '@/components/addressSelect/addressSelect'
import DragUpload from '@/components/DragUpload/DragUpload'
import { editDisSMPoint, disSMPoint } from '@/api/distributorPoints'
import checkInfo from '@/utils/checkInfo'

export default {
    name: 'pointActive',
    components: {
        addressSelect,
        DragUpload
    },
    computed: {
        ...mapState(['themes']),
        // 渐变背景颜色
        bg01() {
            return `rgba(${colorRgb(this.themes.color).r}, ${colorRgb(this.themes.color).g}, ${colorRgb(this.themes.color).b}, 0.1) !important`
        },
        // 渐变边框颜色
        br04() {
            return `rgba(${colorRgb(this.themes.color).r}, ${colorRgb(this.themes.color).g}, ${colorRgb(this.themes.color).b}, 0.4) !important`
        }
    },
    watch: {},
    data() {
        return {
            timeTitle: '', // 时间弹窗标题
            timeVisible: false, // 时间弹窗

            addressShow: false, // 地址选择器
            defaultValue: [], // 默认地址

            // 周几列表
            daysList: ['一', '二', '三', '四', '五', '六', '日'],

            addressName: '', // 选择的省市区名字
            choosePoint: '', // 地图选择地点的对象

            businessHours: [{ begin: '', end: '' }], // 时间段
            type: 'begin', // 选择的begin/end
            timeIndex: '', // 所选择的时间下标

            // 表单字段
            id: '', // id
            pointName: '', // 自提点名称
            contactPhone: '', // 联系人电话
            longitude: '', // 经度
            latitude: '', // 纬度
            period: [], // 已选择的周几集合
            sinceMentionPic: [], // 图片集合
            addressId: '', // 省市区id数组
            sinceMentionAddr: '', // 详细地址

            fistActive: 'false' // 是否第一次激活
        }
    },
    activated() {
        if (sessionStorage.getItem('location')) {
            this.choosePoint = JSON.parse(sessionStorage.getItem('location'))
            this.longitude = this.choosePoint.location.lng
            this.latitude = this.choosePoint.location.lat
        }

        const queryId = this.$route.query.id

        // 判断id是否传过来
        if (!queryId && !this.fistActive) {
            this.resetData()
        }

        // 如果id存在并且不等于缓存的id，则获取详情
        if (queryId && this.id != queryId) {
            this.id = queryId
            this.getDetail()
        }
    },
    // 导航离开该组件的对应路由时调用
    beforeRouteLeave(to, from, next) {
        if (to.name == 'pointIndex') {
            this.resetData()
        }
        next()
    },
    mounted() {
        if (this.$route.query.id) {
            this.id = this.$route.query.id
            this.getDetail()
        }
        if (this.$route.query.first) {
            this.fistActive = true
        }
    },
    methods: {
        // 获取详情
        getDetail() {
            disSMPoint()
                .then((res) => {
                    if (!res.success) return void this.$toast(res.msg)

                    const address = res.result.sinceMentionDetailAddr.split(' ')

                    this.pointName = res.result.pointName
                    this.contactPhone = res.result.contactPhone
                    this.longitude = res.result.longitude // 经度
                    this.latitude = res.result.latitude // 纬度
                    this.period = res.result.period.split(',').map((item) => Number(item))
                    this.sinceMentionPic = res.result.sinceMentionPicList
                    this.addressId = [res.result.provinceId, res.result.cityId, res.result.areaId, res.result.townsId]
                    this.sinceMentionAddr = res.result.sinceMentionAddr
                    this.choosePoint = {
                        name: res.result.choosePointName,
                        location: {
                            lng: Number(res.result.longitude),
                            lat: Number(res.result.latitude)
                        }
                    }
                    this.addressName = `${address[0]} ${address[1]} ${address[2]} ${address[3]}`
                    this.businessHours = JSON.parse(res.result.businessHours)
                    // 选择的地区回显
                    this.defaultValue = [
                        { name: address[0], key: res.result.provinceId },
                        { name: address[1], key: res.result.cityId },
                        { name: address[2], key: res.result.areaId },
                        { name: address[3], key: res.result.townsId }
                    ]
                })
                .catch((err) => {
                })
        },

        // 去选择地址
        goChoose() {
            this.addressShow = true
        },

        // 去自选地址
        goChooseAddress() {
            let position = {}
            if (this.choosePoint) {
                position = { lng: this.choosePoint.location.lng, lat: this.choosePoint.location.lat }
            }
            this.$router.push({ name: 'map', query: { source: 'point', ...position } })
        },

        // 点击了选择省市区地址触发
        onAddress(event) {
            this.addressId = event.keyId
            this.addressName = event.addressStr
        },

        // 点击验证按钮
        submit() {
			if (
			    !checkInfo([
			        { type: 'hasValue', value: this.pointName, msg: '请输入自提点名称' },
			        { type: 'hasValue', value: this.contactPhone, msg: '请输入联系电话' },
			        { type: 'phone', value: this.contactPhone, msg: '请输入正确的联系电话' },
			        { type: 'hasValue', value: this.addressId, msg: '请选择省市区' },
			        { type: 'hasValue', value: this.longitude, msg: '请选择地理位置' },
			        { type: 'hasValue', value: this.latitude, msg: '请选择地理位置' },
			        { type: 'hasValue', value: this.choosePoint.name, msg: '请选择地理位置' },
			        { type: 'hasValue', value: this.sinceMentionAddr, msg: '请输入详细地址' },
			        { type: 'hasValue', value: this.period, msg: '请选择营业时间' },
			        { type: 'hasValue', value: this.sinceMentionPic, msg: '请上传图片' }
			    ])
			) {
			    return
			}
			
			let timeError = false
			for (let item of this.businessHours) {
			    if (!(item.begin && item.end)) {
			        timeError = true
			        break
			    }
			}
			if (timeError) return void this.$toast('请选择时间段')
           this.$utils.uDebounce(() => {
			   editDisSMPoint({
			       pointName: this.pointName,
			       contactPhone: this.contactPhone,
			       provinceId: this.addressId[0],
			       cityId: this.addressId[1],
			       areaId: this.addressId[2],
			       townsId: this.addressId[3],
			       longitude: this.longitude,
			       latitude: this.latitude,
			       choosePointName: this.choosePoint.name,
			       sinceMentionAddr: this.sinceMentionAddr,
			       period: this.period.join(','),
			       businessHours: JSON.stringify(this.businessHours),
			       sinceMentionPic: this.sinceMentionPic,
			       sinceMentionDetailAddr: this.addressName + ' ' + this.sinceMentionAddr
			   })
			       .then((res) => {
			           if (!res.success) return void this.$toast(res.msg)
			   
			           this.$toast({
			               message: '提交成功',
			               onClose: () => {
			                   sessionStorage.removeItem('location')
			                   this.$router.replace({ path: '/pointIndex' })
			               }
			           })
			       })
			       .catch((err) => {
			       })
		   })
        },

        // 弹出时分选择器
        selectTime(str, type, index) {
            this.timeVisible = true
            this.timeTitle = str
            this.type = type
            this.timeIndex = index
        },

        // 确认时分
        confirmTime(value) {

            let activeTimeObj = this.businessHours[this.timeIndex]
            let activeTimeBegin = new Date().setHours(activeTimeObj.begin.split(':')[0], activeTimeObj.begin.split(':')[1])
            let nowTime = new Date().setHours(value.split(':')[0], value.split(':')[1])

            if (activeTimeBegin >= nowTime && this.type == 'end') {
                return void this.$toast('结束时间不可大于或等于开始时间')
            }

            if (this.timeIndex != 0) {
                if (
                    this.type == 'begin' &&
                    nowTime <=
                        new Date().setHours(
                            this.businessHours[this.timeIndex - 1].end.split(':')[0],
                            this.businessHours[this.timeIndex - 1].end.split(':')[1]
                        )
                ) {
                    return void this.$toast('当前开始时间不可小于或等于上一个时间的结束时间')
                }
            }

            this.businessHours[this.timeIndex][this.type] = value
            this.timeVisible = false

        },

        // 添加时间
        addTime() {
            if (this.businessHours.length >= 3) {
                return
            }
            if (!this.businessHours[this.businessHours.length - 1].begin) {
                this.$toast('请选择开始时间')
                return
            }
            if (!this.businessHours[this.businessHours.length - 1].end) {
                this.$toast('请选择结束时间')
                return
            }

            this.businessHours.push({
                begin: '',
                end: ''
            })
        },

        // 删除时间
        deleteTime(index) {
            this.businessHours.splice(index, 1)
        },

        // 选择/取消时间点
        toggleDay(dayIndex) {
            if (this.period.includes(dayIndex)) {
                this.period = this.period.filter((item) => item != dayIndex)
            } else {
                this.period.push(dayIndex)
            }
        },

        // 用于提交表单后需要清除数据，防止缓存
        resetData() {
            this.id = '' // id
            this.pointName = '' // 自提点名称
            this.contactPhone = '' // 联系人电话
            this.longitude = '' // 经度
            this.latitude = '' // 纬度
            this.period = [] // 已选择的周几集合
            this.sinceMentionPic = [] // 图片集合
            this.addressId = '' // 省市区id数组
            this.sinceMentionAddr = '' // 详细地址

            this.addressName = ''
            this.choosePoint = ''
            this.businessHours = [{ begin: '', end: '' }] // 时间段
            this.type = 'begin' // 选择的begin/end
            this.defaultValue = []
        }
    }
}
</script>

<style>
.van-cell {
    padding: 15px 10px 15px 10px;
}
input::-webkit-input-placeholder {
    color: #cccccc;
}
.van-field__label {
    margin-right: 15px;
}

.selectedDay {
    color: var(--themescolor);
}
</style>
